﻿/// <reference path="jquery-1.5.1.min.js" />
/// <reference path="global.variable.js" />
/// <reference path="three-column.helper.js" />



$(document).ready(function () {




    var target_center = $(div_center_list).first();


    //ajax start
    $(document).ajaxStart(function () {
        jQuery.ShowLoading();



        myLayout.close('south');
        //jQuery.GetCoulmn('south').css('background-color', '#FFFFFF');
        if ($(div_error_span).length) {
            //$("div.ErrorBar").hide();
            //$("div.ErrorBar").html('');
            $(div_error_span).html('');
        }
    });



    $(document).ajaxStop(function () {
        jQuery.HideLoading();
        FoucsDefaultControl();
        //FocusArticlePageControl();

    });

    $(document).ajaxComplete(function () {
        FoucsDefaultControl();
    });

    //ajax error
    $(document).ajaxError(function (event, XMLHttpRequest, ajaxOptions, thrownError) {
        //alert('ajaxError');

        jQuery.HandelAjaxError(XMLHttpRequest, ajaxOptions, thrownError);
    });


    $("a.AjaxCentre").live("click", function (event) {
        event.preventDefault();

        var count = $(tab_id).tabs('length');
        if (count < 1) {
            $(tab_id).tabs("add", tab_0_id, $(this).text());
        }


        var href = $(this).attr("href");
        //east_container
        //AjaxCall(href, tab_0_id, east);
        AjaxCall(href, tab_0_id, east_container);

        if (!myLayout.state.east.isClosed) {
            myLayout.close('east');
        }
        $(tab_id).tabs('label', 0, $(this).text());
        SetToOrDefaultTab(0);


        return false;
    });


    $("div.AjaxCentre").live("click", function (event) {
        event.preventDefault();

        var count = $(tab_id).tabs('length');
        if (count < 1) {
            $(tab_id).tabs("add", tab_0_id, $(this).text());
        }
        var href = $(this).attr("href");

        AjaxCallWithSuccess(href, jQuery.AjaxCentreSuccess, tab_0_id);



        $(tab_id).tabs('label', 0, $(this).text());
        SetToOrDefaultTab(0);
        //AjaxEditCallWithFormData("/User/UserSettings");

        return false;
    });




    function ValidateAndSubmitEasForm() {
        var saveForm = $(div_east_form).validate().form();
        if (saveForm) {
            SubmitEastForm();
        }
    }

    $(".CompanySaveButton").live("click", function () {

        if ($('#companyNameInDb').val().length>0) {


            if ($('#companyNameInDb').val() != $('#Company_CompanyName').val()) {

                var message = $('.CompanySaveButton').attr('message');
                jQuery.Confirm(this, message, ValidateAndSubmitEasForm);
                event.stopImmediatePropagation();
                return false;
            }
        }

    });





    /*
    *this will submit all the forms having( div_center_search_form class)
    *
    * 
    */
    $(".AjaxSubmitEast").live("click", function () {
        //SubmitEastForm();
        var saveForm = $(div_east_form).validate().form();
        if (saveForm) {
            SubmitEastForm();
        }
    });





    function FocusArticlePageControl() {
        if ($(div_article_form_default_foucs)) {
            $(div_article_form_default_foucs).focus();
        }
    }

    //initialization of tabs
    $(function () {
        $("#tabs").tabs({
            select: function (event, ui) // This event is triggered when clicking a tab
            {

                if (ui.index == 1) { // for storyboard

                    LoadStoryBoard(storyBoradTabClickAction);

                }

                if (ui.index == GetTabIndex(name_article)) { // for article
                    loadArticle();
                    FocusArticlePageControl();
                }
            }
        });
    });

    //search from submit to get list data
    $(div_center_search_select).live('change', function () {
        var form = $(div_center_search_form).first();
        var target = $(div_center_list).first();
        var clear = jQuery.GetCoulmn('east-container');
        // alert(target.length);
        AjaxSearchFormPost(form, target, clear);
    });



    // clickicking on logo redirect to home page
    $(".logoImage").live("click", function () {
        var href = $(this).attr("href");
        if (href) {
            jQuery.Url(href);
        }
    });





});                                       //end of doc ready


function ShowError(errMsg) {
    jQuery.HideLoading();

    var message = $("<div class='message'></div>").html(errMsg);

    $(div_error_span).html(message);
   // $(div_error_span).find('style').remove();
    $(div_error).show();
    myLayout.open('south');
}

function SubmitEastForm() {
	var searchForm = $(div_center_search_form);

	//this is east form
	var saveForm = $(div_east_form);

	var data;
	var action;


	//data = saveForm.serialize();

	if (saveForm) {
		if (searchForm) {
			data = searchForm.serialize() + '&' + saveForm.serialize();
		}

		action = saveForm.attr("action");
		AjaxSaveAndLoadList(data, action, div_center_list, jQuery.GetCoulmn('east-container'));

	}

	return false;
}


	//Search form post
	//param is from jQuery form select
	//param is from jQuery target select
function AjaxSearchFormPost(form, target, clear) {    
		if (typeof (form) == "string") {
			form = $(form);
		}

		if (typeof (target) == "string") {
			target = $(target);
		}

		var action = $(form).attr('action');
		var data = form.serialize();   



		AjaxPost(data, action, target, clear);
	}

	//AjaxSaveAndLoadList form post

	function AjaxSaveAndLoadList(data, action, target, clear) {

		AjaxPost(data, action, target, clear);

	}



	function AjaxPost(data, action, target, clear, afterSucessCallback) {
		if (typeof (target) == "string") {
			target = $(target);
		}

		if (clear) {
			if (typeof (clear) == "string") {
				clear = $(clear);                
			}

		}
		action=  jQuery.CreateAjaxUrl(action);
		//data =  jQuery.CreateAjaxUrl(data);

		$.ajax({
			type: 'POST',
			url: action,
			data: data,
			success: function (data, textStatus, XMLHttpRequest) {
				jQuery.Success(data, textStatus, XMLHttpRequest, target, clear,NaN,NaN,afterSucessCallback);
                //data, textStatus, XMLHttpRequest, target, clear, append, beforeSucessCallback, afterSucessCallback
			}
		});
	}

	function ShowTab() {
	    $("div.centre").show();
	    $("div.home").remove();
    }


	/*
		Set foucs to default control
		todo:need to set a selector
	*/
	function FoucsDefaultControl(){
	    if ($(div_east_form_default_foucs)) {
	        setTimeout("$('" + div_east_form_default_foucs + "').focus();", 1000);
	    }

	    if ($(div_article_form_default_foucs).length) {
	    
	        if ($('#Article_Id').val() == "0") {
	           // $(div_article_form_default_foucs).focus();

	            setTimeout("$('" + div_article_form_default_foucs + "').focus();", 1000);
            }
	        
        }
	}

	function pausecomp(millis) {
		var date = new Date();
		var curDate = null;

		do { curDate = new Date(); }
		while (curDate - date < millis);
	} 

//    /*
//    This method is called when there is search form 
//    */

	function AjaxEditCallWithFormData(action) {
		//var div_center_search_form = '.ui-layout-center .searchfrom form:first';
		var valid = $(div_center_search_form).first().validate().form();	
		if (valid) {
			var data = $(div_center_search_form).first().serialize();

			//create action
			action = CrearteUrl(action, data);

			AjaxCall(action, jQuery.GetCoulmn('east-container'));
		   //AjaxCall(action, east_container);

			myLayout.open('east');
			ClearTabOnPublicationRowClick()
            
			


		}
		
		return false;
	}



	function AjaxDeleteCallWithFilter(action, message) {


		DeleteItem = function (sender) {
			var data;
			if ($(div_center_search_form)) {
				data = $(div_center_search_form).first().serialize();
				action = CrearteUrl(action, data);
			}

			AjaxCall(action, div_center_list , div_east_form);
	};

		 //var message = "Are you sure you want to delete this object?";
		 jQuery.Confirm(this, message, DeleteItem);
		 return false;

	}



	//Set tabs
	function SetToOrDefaultTab(num) {
		if (!num) {
			num = 0;
		}
		var $tabs = $(tab_id).tabs();
		$tabs.tabs('select', num); // switch to tab
	}

   
	function AjaxCall(action, target,clear) 
	{
		$.ajax({
			url: jQuery.CreateAjaxUrl(action),
			success: function (data, textStatus, XMLHttpRequest) {

				if (typeof (clear) == "string") {
					clear = $(clear);
				}

				jQuery.Success(data, textStatus, XMLHttpRequest, target);

				if (clear) {
					clear.html('');
					if (!myLayout.state.east.isClosed) 
					 {
						myLayout.close('east');
					 }

				}
			}
			
		});
    }

    //this method used for ajax call with callback before and after sucess
    function AjaxCallWithCallback(action, target, clear, beforeSucessCallBack, afterSucessCallBack) {
        $.ajax({
            url: jQuery.CreateAjaxUrl(action),

            success: function (data, textStatus, XMLHttpRequest) {

                if (typeof (clear) == "string") {
                    clear = $(clear);
                }

                //jQuery.Success(data, textStatus, XMLHttpRequest, target);
                jQuery.Success(data, textStatus, XMLHttpRequest, target, clear, NaN, beforeSucessCallback, afterSucessCallback)

                if (clear) {
                    clear.html('');
                    if (!myLayout.state.east.isClosed) {
                        myLayout.close('east');
                    }
                }
            }

        });
    }

    //this method used for ajax call with callback after sucess
    function AjaxCallWithAfterSucessCallback(action, target, clear,  afterSucessCallBack) {
        $.ajax({
            url: jQuery.CreateAjaxUrl(action),

            success: function (data, textStatus, XMLHttpRequest) {

                if (typeof (clear) == "string") {
                    clear = $(clear);
                }


                //Success(data, textStatus, XMLHttpRequest, target, clear, true, NaN, afterSucessCallBack)
                             //(data, textStatus, XMLHttpRequest, target, clear, append, beforeSucessCallback, afterSucessCallback)
                jQuery.Success(data, textStatus, XMLHttpRequest, target, clear, false, NaN, afterSucessCallBack)

                if (clear) {
                    clear.html('');
                    if (!myLayout.state.east.isClosed) {
                        myLayout.close('east');
                    }
                }
            }

        });
    }

    function AjaxCallAppendCallWithAfterSucessCallback(action, target,clear, afterSucessCallBack) 
	{
		$.ajax({
			url: jQuery.CreateAjaxUrl(action),
			success: function (data, textStatus, XMLHttpRequest) {

				if (typeof (clear) == "string") {
					clear = $(clear);
				}

			//	jQuery.Success(data, textStatus, XMLHttpRequest, target, NaN, true);
                //function (data, textStatus, XMLHttpRequest, target, clear, append, beforeSucessCallback, afterSucessCallback)
                jQuery.Success(data, textStatus, XMLHttpRequest, target, clear, true, NaN, afterSucessCallBack);
				if (clear) {
					clear.html('');					
					myLayout.close('east');
					
				}
			}
			
		});
	}



    function AjaxCallWithSuccess(action,onSuccess,target) 
    {
        $.ajax({
            url: jQuery.CreateAjaxUrl(action),
            success: function (data, textStatus, XMLHttpRequest)
             {
                if (onSuccess) 
                {
                    onSuccess(data,textStatus,XMLHttpRequest,target);
                }



            }

        }); 
    }


	function AjaxCallAppendCall(action, target,clear) 
	{
		$.ajax({
			url: jQuery.CreateAjaxUrl(action),
			success: function (data, textStatus, XMLHttpRequest) {

				if (typeof (clear) == "string") {
					clear = $(clear);
				}

				jQuery.Success(data, textStatus, XMLHttpRequest, target, NaN, true);

				if (clear) {
					clear.html('');					
					myLayout.close('east');
					
				}
			}
			
		});
	}




    function LogOut() {

	    window.location = "../Login/Logout";
	    jQuery.HideLoading();
    }

    function applyEnter(e)
    {
	     e = e||window.event;
	    if (e.keyCode == 13)
	    {
		    $('.AjaxSubmitEast').click();
	    }
    }

    function ApplyArticleEnter(e,button) {
        e = e || window.event;
        var foucs= $("*:focus").attr("id");
        if (e.keyCode == 13 && $(button).length && (foucs !="Article_Comments")) {
            //alert($("*:focus").attr("id"));
            $(button).click();
        }
    }

    function ApplySubArticleEnter(e, button) {
        e = e || window.event;
        var foucs = $("*:focus").attr("id");
        if (e.keyCode == 13 && $(button).length && (foucs != "Comments")) {
            //alert($("*:focus").attr("id"));
            $(button).click();
        }
    }
 



    (function ($) {



   
	    jQuery.extend({
		    South: function(){	   
		        return $(south).last();		
	        }
	    });

	
	    jQuery.extend({

		    GetCoulmn: function(column){
		
		        var col = center;
			   
		        if(column == "north" || column =='north'){
			        col = north;
		        }
		        else if(column == "south" || column =='south'){
			        col = south;
		        }
		        else if(column == "east" || column =='east'){
			        col = east;            
		        }
		        else if(column == "east-container" || column =='east-container'){
			        //col = east;
			        col = east_container;
		        }
		        else if(column == "west" || column =='west'){
			        col = west;
		        }
		        else if(column == "center" || column =='center'){
			
		        }
		        return $(col);
		
	        }
	    });

	    jQuery.extend({ //MAW: Just create random number. Add random number end of the url.
		    CreateAjaxUrl: function (url) {
			    if (url) {
				    var start = url.indexOf("r=");
				    if (start >= 0) {
					    var url_new = url.substring(0, start - 1);

					    var end = url.indexOf("&", start + 1);
					    if (end > start) {
						    if (url.length > end) {
							    url_new += url.substring(end, url.length - 1);
						    }
					    }
					    url = url_new;
				    }
				    if (url.indexOf("?") >= 0) {
					    url += "&";
				    }
				    else {
					    url += "?";
				    }
				    url += "r=" + Math.random();
			    }

			    return url;
		    }
	    });

	    jQuery.extend({
		    //AjaxResponse will contain the response type
		    AjaxResponse: function (XMLHttpRequest) {
			    this.ContentType = (XMLHttpRequest.getResponseHeader("content-type") || "").toLowerCase();
			    this.IsContentHtml = this.ContentType.indexOf("html") >= 0;
			    this.IsContentJS = this.ContentType.indexOf("javascript") >= 0;
			    this.IsContentJSON = this.ContentType.indexOf("json") >= 0;
			    this.Content = XMLHttpRequest.responseText;
		   
		    }
	    });



	    //Ajax success
	    jQuery.extend({
		     Success: function (data, textStatus, XMLHttpRequest, target, clear, append, beforeSucessCallback, afterSucessCallback){

                //this function is called before sucess
                if(beforeSucessCallback)
                {
                    beforeSucessCallback();
                }

			    var doClear = true;
			    if(target){
				
				    if (typeof (target) == "string") {
					     target = $(target);
				     }


				    var ajaxResponse = new jQuery.AjaxResponse(XMLHttpRequest);

				    if(ajaxResponse.IsContentHtml){
					
					    if(append){						
						    target.append(ajaxResponse.Content);  
						    target.parents().each( function (){							
							    if( $(this).attr('scrollHeight')>$(this).height())
							    {
                                    $(this).scrollTop($(this).attr('scrollHeight'));
								    return false;
							    }
						    });
					    }
					    else{
						    target.html(ajaxResponse.Content);                    
					    }	
					
					
                        ShowTab();
					
                        //this function is called before sucess
                        if(afterSucessCallback)
                        {
                            afterSucessCallback();
                        }                    
                    			
				    }

				     else if(ajaxResponse.IsContentJS){
				      // alert(ajaxResponse.Content);
				   
				       if(ajaxResponse.Content.indexOf('LogOut')>-1){
					    LogOut();
				       }

				   
				   
				     }
				    else if(ajaxResponse.IsContentJSON){
					    myLayout.open('south');
					    doClear = false;
					    try {
					
						    var result = jQuery.parseJSON(XMLHttpRequest.responseText);
									   
						    var message = $("<div class='message'></div>").html('Notification: '+ result.Message);
								    $(div_error).show();
								    $(div_error_span).html(message);

					    }
					    catch (ex) {
					
						    var message = $("<div class='message'></div>").html(ex.ToString());
						    $(div_error_span).html(message);
					    }
				     }
                     else
                     {
                        if(target){
                            $(target).html('');
                        }
                     }

				    if(clear && doClear)
				    {
					
					    if (typeof (clear) == "string") 
					    {
						    clear = $(clear);
					    }

					    clear.html('');
					      if (!myLayout.state.east.isClosed) 
					     {
						    myLayout.close('east');
					     }
				    }
			    }
		     }
	    });


	    jQuery.extend({
		    //jQuery.HandelAjaxError will handel ajax error and show error message
		    HandelAjaxError: function (XMLHttpRequest, ajaxOptions, thrownError) {
			    try {
					     if($(div_error).length){	
                     				
						    myLayout.open('south');					
						    var x =  jQuery.GetCoulmn('south');
					   
						    if(x.length)
						    {
							    //x.css('background-color','#FFB6C1');
						    }
						

						    $(div_error).show();
						
						    var ajaxResponse = new jQuery.AjaxResponse(XMLHttpRequest);

						    if (ajaxResponse.IsContentJSON) {
							    try {

								    var error = jQuery.parseJSON(XMLHttpRequest.responseText);
								    var message = $("<div class='message'></div>").html('Error: '+ error.Message);
								    $(div_error).show();

								    $(div_error_span).html(message);

							    }
							    catch (ex) {
								
								    var message = $("<div class='message'></div>").html('Error: '+thrownError);
								    $(div_error_span).html(message);
							    }
						    }
						    else if (ajaxResponse.IsContentHtml) {

							    var t = ajaxResponse.Content;

							    $(div_error_span).html(t);
							    $(div_error_span).find('style').remove();
						    }
						    else if (ajaxResponse.IsContentJS) {
							    if(ajaxResponse.Content.indexOf('LogOut')>-1){
								    LogOut();
							    }
						    }
                            else
                            {
                                    jQuery.HideLoading();
                                
                                    var message = $("<div class='message'></div>").html('Error: Internal server error. Please contact with admin..');
								    $(div_error).show();
								    $(div_error_span).html(message);
                            }

					     }
						
			    }

			    catch (ex) { }
		    }
	    });


	    jQuery.extend({
	        Confirm: function (sender, message, callback) {
		        if (message) {
			        var confirmed = false;
                    $("div#ConfirmDialog div.confirm-message").html(message);
			        $("div#ConfirmDialog div.yes-button").unbind("click").bind("click", function () {
				        if (!confirmed) {
					        $("div#ConfirmDialog").dialog("close");
					        if (callback) {
						        callback(sender);
					        }
				        }
				        confirmed = true;
			        });

			        $("div#ConfirmDialog div.no-button").unbind("click").bind("click", function () {
				        if (!confirmed) {
					        $("div#ConfirmDialog").dialog("close");
				        }
				        confirmed = true;
			        });

			        $("div#ConfirmDialog").dialog({
				        //show: "scale",
			            // hide: "scale",
				        modal: true,
				        closeOnEscape: true,
				        resizable: false,
				        draggable: true,
				        position: "center",
				        autoOpen: true,
				        stack: true,
				        height: "auto",
				        minHeight: 0,
				        //open: function () { setTimeout('$("div#ConfirmDialog").dialog("close");', 5000); },
				        close: function (event, ui) { $("div#ConfirmDialog div.confirm-message").html(""); },

				        dialogClass: "PPDSDialog"
			        });
		        }
	        }
        });
    })(jQuery);

